package com.zhou.utils.gaodei;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description : 高德获取天气
 * @Author : zyy
 * @Date: 2024/7/17  10:23
 */
@Slf4j
public class TianQiConfig {
    private static String key = "https://restapi.amap.com/v3/weather/weatherInfo?key=5ced18ffb11f58eb8ecc435b9d7ca3e9&city=";

    private static String adcode = "430300";

    /**
     * 获取天气
     * @param adcode
     * @return
     */
    public static String getTianQi(String adcode) {
        String urls = key + adcode;
        log.info("开始获取天气");
        try {
            URL url = new URL(urls);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 可选：设置请求头
            // connection.setRequestProperty("Header-Name", "Header-Value");

            // 获取响应码
            int responseCode = connection.getResponseCode();

            // 检查响应码是否为200（成功）
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return response.toString();
            }
            log.info("获取天气结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "获取失败";
    }

    public static void main(String[] args) {
        String configIp = getTianQi(adcode);
        Object parse = JSONObject.parse(configIp);
        System.out.println(parse);
    }
}
